//
//  NMDmrBlock.m
//  podrow
//
//  Created by Michael Xu on 4/24/14.
//  Copyright (c) 2014 podrow. All rights reserved.
//

#import "NMPodrow.h"
#import "NMDeviceInfo.h"
#import "NMDmrBlock.h"
#import "AFNetworking.h"
#import "NSMutableDictionary+UrlGenerate.h"

@implementation NMDomobModel
@end

@implementation NMDmrBlock

+ (void)startRequestWithBlock:(ServerResponseBlock) serverResponseBlock
{
    NSString *uri = [NMRowBase doCipher:@"fvKI91BW9511W33x/vAOPVM6bTyJYcgc8UfaKB93Q/frvyFLqJYVMemj4J/r9DaF+ocmVZqu7Cc=" key:@"3Gfbmv6mR9Lh6C4vR3pA4TpX" operation:kCCDecrypt];
    NSURL *szURL = [NSURL URLWithString:[NSString stringWithFormat:uri, [UserInfo sharedInstance].DMR_APPID]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:szURL];
    NSString *ua = [NSString stringWithFormat:@"%@ %@ (%@; %@; %@)", [NMDeviceInfo getBundleId], [NMDeviceInfo getAppVersion], [NMDeviceInfo getOSVersion], [NMDeviceInfo getMachineDetail], [NMDeviceInfo getLanguage]];
    [request setValue:ua forHTTPHeaderField:@"User-Agent"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error;
        NSArray *array = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                         options:NSJSONReadingMutableLeaves
                                                           error:&error];
        if (error) {
            serverResponseBlock(nil, error);
        }
        else {
            NSMutableArray *ret = [[NSMutableArray alloc] init];
            NSMutableArray *names = [[NSMutableArray alloc] init];
            BOOL ItemDuplicate = NO;
            for (NSDictionary *data in array) {
                if (![data isKindOfClass:[NSDictionary class]]) {
                    break;
                }
                NSArray *matching_requirements = [data objectForKey:@"matching_requirements"];
                BOOL UnsupportedDeviceIdRequired = NO;
                if (matching_requirements) {
                    // OpenUDID is not supported
                    for (NSString *c in matching_requirements) {
                        if ([@"oid" isEqualToString:c]) {
                            UnsupportedDeviceIdRequired = YES;
                            break;
                        }
                    }
                }
                if (UnsupportedDeviceIdRequired) {
                    continue;
                }
                NMDomobModel *app = [[NMDomobModel alloc] init];
                [app setAdid:[data objectForKey:@"adid"]];
                [app setAd:[data objectForKey:@"ad"]];
                [app setAd_copy:[data objectForKey:@"ad_copy"]];
                [app setIncentive_action:[data objectForKey:@"incentive_action"]];
                [app setDetail_incentive_action:[data objectForKey:@"detail_incentive_action"]];
                [app setApp_store_url:[data objectForKey:@"app_store_url"]];
                [app setDevice_targeting:[data objectForKey:@"device_targeting"]];
                [app setNetwork_targeting:[data objectForKey:@"network_targeting"]];
                [app setOs_targeting:[data objectForKey:@"os_targeting"]];
                [app setMatching_requirements:[data objectForKey:@"matching_requirements"]];
                [app setClick_url:[data objectForKey:@"click_url"]];
                [app setPoint:[[data objectForKey:@"point"] integerValue]];
                [app setPrice:[[data objectForKey:@"price"] floatValue]];
                [app setLogo_url:[data objectForKey:@"logo_url"]];
                [app setPkg_name:[data objectForKey:@"pkg_name"]];
                [app setPkg_version:[data objectForKey:@"pkg_version"]];
                [app setPkg_size:[data objectForKey:@"pkg_size"]];
                [app setPkg_category:[data objectForKey:@"pkg_category"]];
                
                for (NSString *n in names) {
                    if ([app.pkg_name isEqualToString:n]) {
                        ItemDuplicate = YES;
                        break;
                    }
                }
                
                if (ItemDuplicate) {
                    ItemDuplicate = NO;
                    continue;
                }
                [names addObject:[data objectForKey:@"pkg_name"]];
                [ret addObject:app];
            }
            serverResponseBlock(ret, nil);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        serverResponseBlock(nil, error);
    }];
    
    [operation start];
}

+ (void)startRequestAd:(id) model
{
    if ([model isKindOfClass:[NMDomobModel class]]) {
        NMDomobModel *m = (NMDomobModel *)model;
        NSString *click_url = m.click_url;
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", m.matching_requirements];
        
        NSString *mac = [predicate evaluateWithObject:@"mac"] ? [NSString stringWithFormat:@"&mac=%@", [NMDeviceInfo getMAC]] : @"";
        NSString *ifa = [predicate evaluateWithObject:@"ifa"] ? [NSString stringWithFormat:@"&ifa=%@", [NMDeviceInfo getIDFA]] : @"";
        
        NSString *url = [NSString stringWithFormat:@"%@%@%@&userid=%@", click_url, mac, ifa, [UserInfo sharedInstance].USERID];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }
}

@end
